package com.jierui.meter.frontend.domain;

import com.jierui.meter.frontend.base.enums.BaseEnum;

import java.util.LinkedHashMap;

public class EnumUtils {
    /**
     *
     * @param enumClass
     * @param obj isValid: 0 or isValid: {value: 0, name: ""}
     * @param <T>
     * @return
     */
    public static <T extends Enum<?> & BaseEnum> T valueOf(Class<T> enumClass, Object obj) {
        String value = null;
        if (obj instanceof Integer) {
            value = (String) obj;
        } else if (obj instanceof LinkedHashMap) {
            Object v = ((LinkedHashMap) obj).get("value");
            value = String.valueOf(v);
        } else {
            try {
                value = String.valueOf(obj);
            } catch (Exception e) {
                return null;
            }
        }
        T[] enumConstants = enumClass.getEnumConstants();
        for (T t : enumConstants) {
            if (t.getValue().equals(value)) {
                return t;
            }
        }
        return null;
    }

    public static boolean isEqual(BaseEnum source, BaseEnum dest) {
        if (source == null || dest == null) return false;
        if (source.getValue() == null || dest.getValue() == null) return false;
        return source.getValue().equals(dest.getValue());
    }
    
	public static String getValue(Object obj) {
		if (obj instanceof BaseEnum) {
			return ((BaseEnum) obj).getValue();
		}
		return null;
	}
}
